package gen.tools.deploy;

import gen.tools.Widgets;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.jboss.as.cli.CommandContext;
import org.jboss.as.controller.client.ModelControllerClient;
import org.jboss.dmr.ModelNode;
import org.tmatesoft.svn.core.SVNProperties;
import org.tmatesoft.svn.core.SVNURL;
import org.tmatesoft.svn.core.io.SVNRepository;
import org.tmatesoft.svn.core.io.SVNRepositoryFactory;
import org.tmatesoft.svn.core.wc.SVNWCUtil;

public class DepAWE extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    public DepAWE() {
        super();
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request,response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		final Widgets wid = new Widgets();
		request.setCharacterEncoding( wid.UIcodeSet );
		response.setCharacterEncoding( wid.UIcodeSet );
		response.setContentType("application/text");
		
		final int depmainSN = Integer.parseInt( request.getParameter("depmainSN") );
		final String bssId = "fOrder";
		final String subsysId = request.getParameter("subsysId");
		final String envId = request.getParameter("envId");
		final String squadId = request.getParameter("squadId");
		final String fileName = request.getParameter("fn");
		final int fileVer = Integer.parseInt( request.getParameter("ver") );
		/*final String extension = fileName.substring(fileName.lastIndexOf("."), fileName.length() ); 	//副檔名  ex: ".ear" ".war" (含一個點)
		final String tmpFileName = System.currentTimeMillis()+extension;			//為節省記憶體，先寫入磁碟，複制完再刪除
		System.out.println("The temporary file for "+fileName+" is "+ tmpFileName);*/
		
		String res ="取得SVN中的檔案失敗";
		
		Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		final ByteArrayOutputStream baos = new ByteArrayOutputStream();
		FileOutputStream fos = null;
		File df = null;
		
		InputStream inputStream = null;
		CommandContext cmdCtx = null;
		ModelControllerClient client = null;
		ModelNode result = null;
		SVNRepository repo = null;
		final int fdepdetailid = wid.getfDepdetailid(depmainSN);	//取得細項ID
		try {
			
			conn = wid.getConn();
			
			String sql = "SELECT cip,cid,cport,cpwd FROM mpsquadenv WHERE bssId=? AND subsysId=? AND envId=? AND squadId=?";
			ps = conn.prepareStatement(sql);
			ps.setString(1, bssId);
			ps.setString(2, subsysId);
			ps.setString(3, envId);
			ps.setString(4, squadId);
			rs = ps.executeQuery();
			rs.next();
			final String cip = rs.getString("cip");
			final String cid = rs.getString("cid");
			final int cport = rs.getInt("cport");
			final char[] cpwd = rs.getString("cpwd").toCharArray();
			
			
			sql = "INSERT INTO fdepdetail (depmainSN,fdepdetailid,fDepActTypeId,hostIP,squadId,bDT,depFN,envId) VALUES(?,?,?,?,?,?,?,?)";
			ps = conn.prepareStatement(sql);
			ps.setInt(1, depmainSN);
			ps.setInt(2, fdepdetailid);
			ps.setInt(3, 6);		//6Server Group檔案部署
			ps.setString(4, cip);
			ps.setString(5, squadId);
			ps.setTimestamp(6, wid.cDT());
			ps.setString(7, fileName);
			ps.setString(8, envId);
			ps.execute();
			
			System.out.println(squadId+"的Console是："+cip+"，要處理的檔案是："+fileName);
			
			final ArrayList<String> svnConnInfo = wid.getSVN4SubsysConnInfo(subsysId, 7);
			repo = SVNRepositoryFactory.create( SVNURL.parseURIEncoded( svnConnInfo.get(0)) );
			repo.setAuthenticationManager( SVNWCUtil.createDefaultAuthenticationManager(svnConnInfo.get(1),svnConnInfo.get(2) ) );
			System.out.print("準備從SVN讀取檔案...");
			fos = new FileOutputStream (new File(fileName));
			repo.getFile(fileName, fileVer, new SVNProperties(), fos);
			System.out.println("OK");
			res = "驅動AP Server失敗";	//取得SVN成功，先假設AP Server失敗
			System.out.println("取得SVN上的檔案");
			
			df = new File( fileName );
		    fos.close();
		    inputStream = new FileInputStream( fileName ); 
			
			String commandLine = "deploy " + fileName + " --server-groups=" + squadId;

			cmdCtx = wid.initCommandContext(cip, cport, cid, cpwd);
			client = cmdCtx.getModelControllerClient();
			ModelNode requestNode = cmdCtx.buildRequest(commandLine);
			result = client.execute(requestNode);
			res = result.toString().indexOf("{\n    \"outcome\" => \"success\"")!=0?res:"成功";
			System.out.println("部署至AP Server："+cip);
			
			sql = "UPDATE fdepdetail SET eDT=?,depResult=? WHERE depmainSN=? AND fdepdetailid=?";
			ps = conn.prepareStatement(sql);
			ps.setTimestamp(1, wid.cDT() );
			ps.setString(2, result.toString() );
			ps.setInt(3, depmainSN);
			ps.setInt(4, fdepdetailid);
			ps.execute();
			System.out.println("Is file "+fileName+" deleted? "+df.getAbsoluteFile().delete());
		} catch(Exception e) {
			final String sql = "UPDATE fdepdetail SET eDT=?,depResult=? WHERE depmainSN=? AND fdepdetailid=?";
			System.out.println("部署失敗了，問題是因為："+e.toString() );
			try {
				ps = conn.prepareStatement(sql);
				ps.setTimestamp(1, wid.cDT() );
				ps.setString(2, e.toString() );
				ps.setInt(3, depmainSN);
				ps.setInt(4, fdepdetailid);
				ps.execute();
			} catch (SQLException e1) {
				e1.printStackTrace();
			}
			wid.errLog(e);
		} finally {
			try {
				if ( rs !=null ) { rs.close(); }
				if ( ps !=null ) { ps.close(); }
				if ( conn !=null ) { conn.close(); }
			} catch (Exception e) { e.printStackTrace(); }
			if (client != null) { client.close(); }
			if (cmdCtx != null) {
				cmdCtx.disconnectController();
				cmdCtx.terminateSession();
			}
			if (baos != null) {baos.close();}
			if (inputStream != null) {inputStream.close();}
			if (repo != null) {repo.closeSession();}
		}
		
		response.getWriter().write(res);
	}
}
